""" -*- coding: utf-8 -*-"""
import os
from flask import current_app
from werkzeug.utils import secure_filename
from datetime import datetime


def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS']


def generate_filename(project_number, design_phase_name, file_type_name, user_name, original_filename):
    """生成安全的保存文件名"""
    # 获取当前日期
    current_date = datetime.now().strftime("%Y%m%d")

    # 提取文件扩展名
    _, ext = os.path.splitext(original_filename)

    # 构建文件名
    safe_filename = f"{file_type_name}_{current_date}_{user_name}{ext}"
    return secure_filename(safe_filename)


def get_project_file_path(project_number, design_phase_name=None):
    """获取项目文件路径"""
    base_path = current_app.config['UPLOAD_FOLDER']
    project_path = os.path.join(base_path, project_number)

    if design_phase_name:
        design_phase_path = os.path.join(project_path, design_phase_name)
        os.makedirs(design_phase_path, exist_ok=True)
        return design_phase_path

    os.makedirs(project_path, exist_ok=True)
    return project_path